package com.community.utils;

import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;


@Slf4j
public class JWT {

    private static final String SECRET = "community";
    //有效时长
    private static final long EXPIRATION_TIME = 1000 * 60 * 60 * 24 * 10;  //10days

    private static final Algorithm algorithm = Algorithm.HMAC256(SECRET);
    public static String generateToken(String mobile, String uuid){



        return com.auth0.jwt.JWT.create()
                .withClaim("mobile", mobile)
                .withClaim("uuid", uuid)
                .withExpiresAt(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .sign(algorithm)
                ;
    }

    public static String generateRefreshToken(String mobile, String uuid){


        return com.auth0.jwt.JWT.create()
                .withClaim("mobile", mobile)
                .withClaim("uuid", uuid)
                .withExpiresAt(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .sign(algorithm)
                ;
    }


    public static DecodedJWT verifyToken(String token) {
            // 创建算法对象
            Algorithm algorithm = Algorithm.HMAC256(SECRET);

            // 验证并解析 JWT
            return com.auth0.jwt.JWT.require(algorithm)
                    .build()
                    .verify(token);
    }

    public static boolean isValidToken(String token){
        try {
            // 验证并解析 JWT
            DecodedJWT jwt = com.auth0.jwt.JWT.require(algorithm)
                    .build()
                    .verify(token);


            return true; // Token 有效
        } catch (JWTVerificationException e) {
            // Token 无效（过期、签名错误等）
            return false;
        }
    }

    public static String getUserId(HttpServletRequest request){

        DecodedJWT decodedJWT = verifyToken(request.getHeader("Authorization"));
        String id = decodedJWT.getClaim("uuid").asString();
        log.info("该用户的id为：", id);
        return id;
    }

}
